package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author wangzhenjun
 * @date 2022/3/17 15:48
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ProductFeignService feignService;
    @Autowired
    private ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart";



    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String o =(String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(o)) {
            // 2.添加新商品到购物车
            CartItem cartItem = new CartItem();
            // 1.远程查询当前要添加的商品信息
            CompletableFuture<Void> skuInfoTask = CompletableFuture.runAsync(() -> {
                R skuInfo = feignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });

                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setPrice(data.getPrice());
                cartItem.setSkuId(skuId);
                cartItem.setTitle(data.getSkuTitle());
            });

            // 2. 远程查询sku信息
            CompletableFuture<Void> getSkuSaleValues = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = feignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            });
            CompletableFuture.allOf(getSkuSaleValues,skuInfoTask).get();
            String jsonString = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),jsonString);

            return cartItem;
        }
        else {
            // 购物车有次商品，直接修改数量
            CartItem item = JSON.parseObject(o, CartItem.class);
            item.setCount(item.getCount() + num);

            cartOps.put(skuId.toString(),JSON.toJSONString(item));
            return item;
        }

    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartItemOps = getCartOps();
        String s = (String) cartItemOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(s, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Cart cart = new Cart();
        if (userInfoTo.getUserId() != null) {
            // 一登录
            Long userId = userInfoTo.getUserId();
            String cartKey = CART_PREFIX + userId;
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            // 如果临时购物车的数据还没有进行合并
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems != null) {
                // 临时购物车有数据，必要合并到登录的用户购物车
                for (CartItem tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(),tempCartItem.getCount());
                }
                //清空临时购物车
                clearCart(tempCartKey);
            }

            // 获取所有的购物车数据【临时和购物车】
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }else {
            // 没有登录
            String userKey = userInfoTo.getUserKey();
            String cartKey = CART_PREFIX + userKey;
            // 获取临时购物车
            List<CartItem> cartItems = getCartItems(cartKey);


            cart.setItems(cartItems);
        }
        return cart;

    }

    @Override
    public void clearCart(String cartKey) {
        stringRedisTemplate.delete(cartKey);

    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        //获取到我们要操作的购物车
                                BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //获取购物车的一个购物项
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1 ? true : false);
        String str = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), str);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        //获取到我们要操作的购物车
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //获取购物车的一个购物项
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String str = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), str);
    }

    @Override
    public void deleteItem(Long skuId) {
        //获取到我们要操作的购物车
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {

        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            //没登录
            return null;
        } else {
            //登录了
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItemList = getCartItems(cartKey);
            //筛选被选中的购物项 过滤数据
            List<CartItem> collect = cartItemList.stream()
                    .filter(item -> item.getCheck())
                    .map((item) -> {
                        //一定要获取到最新的价格
                        R servicePrice = feignService.getPrice(item.getSkuId());
                        String data = (String) servicePrice.get("data");
                        item.setPrice(new BigDecimal(data));
                        return item;
                    }).collect(Collectors.toList());
            return collect;
        }
    }


    /**
     * 临时购物车数据
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if (values != null && values.size() > 0) {
            List<CartItem> collect = values.stream().map(obj -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 获取到我们操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        }else {
            cartKey = CART_PREFIX +userInfoTo.getUserKey();
        }
        // 获取购物车信息
        BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(cartKey);

        return operations;
    }
}
